<template>
  <view class="container" style="position: relative;">
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">出库单</block>
    </cu-custom>

    <scroll-view scroll-y :class="modalName=='viewModal'?'show':''">
      <view v-if="order_goods_list && order_goods_list.length>0">
        <view class="cu-list menu-avatar no-padding text-center">
          <view class="bg-white text-sm flex margin-top-xs text-center"
            style="padding-right: 5px;border-bottom: 1px solid #f1f1f1;">
            <view style="flex:1">商品</view>
            <view style="width:50px;">数量</view>
            <view style="width:40px;">折扣</view>
            <view style="width:60px;">价格</view>
          </view>
          <view class="cu-item" v-for="(item, i) in order_goods_list" :key="i">
            <view class="cu-avatar radius lg">{{item.shouzi}}</view>
            <view class="content text-left">
              <view class="text-grey">{{item.goodsName}}
              </view>
              <view class="text-gray">
                <text class="text-green text-bold padding-right" v-if="item.goodsSpec">{{item.goodsSpec}}</text>
                <text>¥ {{item.goodsPrice}}</text>
              </view>
            </view>
            <view class="action" style="width:50px;">
              <input placeholder="0" name="input" v-model="item.goodsNumber" @input="doUpdateOrderItemAmount"></input>
            </view>
            <view class="action" style="width:40px;">
              <input name="input" v-model="item.discount" @input="doUpdateOrderItemAmount"></input>
            </view>
            <view class="action text-center" style="width:60px;">
              ¥ {{item.goodsAmount}}
            </view>
          </view>
        </view>

        <view class="bg-white margin-top">
          <view class="cu-list menu text-left solid-top">
            <view class="cu-item">
              <view class="content">
                总体折扣
              </view>
              <view class="action text-right">
                <input placeholder="折扣" name="input" v-model="order_discount"></input>
              </view>
              <view class="action padding-left">
                <button class='cu-btn bg-blue shadow' style="width: 100%;" @tap="doUpdateOrderItemDiscount">更新</button>
              </view>
            </view>
          </view>
        </view>

        <view class="bg-white">
          <view class="cu-list menu text-left solid-top">
            <view class="cu-item">
              <view class="content">
                商品数量
              </view>
              <view class="action text-red text-bold text-lg">
                {{order_info.goods_count}}
              </view>
            </view>

            <view class="cu-item">
              <view class="content">
                总价
              </view>
              <view class="action text-red ">
                <text class="padding-right-xs">¥</text> <text
                  class="text-bold text-lg">{{order_info.goodsAmount}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- <view class="margin-top bg-white padding arrow">
        选择收货人
      </view> -->

      <view class="padding">
        <view class="flex ">
          <button class='cu-btn bg-blue shadow' style="width: 100%;" @tap="doShowGoodsModal">+ 加商品</button>
          <!-- <button class='cu-btn bg-brown shadow' style="width: 50%;" @tap="doShowGoodsModal">选择收货人</button> -->
        </view>
        <view class="padding-top" v-if="order_goods_list && order_goods_list.length>0">
          <button class='cu-btn lg bg-green shadow' style="width: 100%;" @tap="doSaveOrder">保存单据</button>
        </view>
      </view>

      <view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
        <view class="cu-dialog">

          <view class="padding-xl">
            <view>您要拨打电话么？</view>
            <view>号码：{{phone}}</view>
            <br />
          </view>

          <view class="cu-bar bg-white">
            <view class="action margin-0 flex-sub text-green " @tap="makeCall">
              <text class="cuIcon-phone"></text>拨打电话
            </view>
            <view class="action margin-0 flex-sub text-green solid-left" @tap="modalName=''">取消</view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="cu-modal bottom-modal" :class="modalName=='goods_select_modal'?'show':''">
      <view class="cu-dialog" @tap.stop="">
        <view class="cu-bar bg-white">
          <view class="action text-blue" @tap="hideModal">取消</view>
          <view class="action text-green" @tap="doUpdateCard">确定</view>
        </view>
        <view class="grid col-3 padding-sm">
          <view v-for="(item,index) in erpGoodsResult.records" class="padding-xs" :key="index">
            <button class="cu-btn orange block" :class="item.checked?'bg-orange':''" @tap="doSelectGoods(item)"
              :data-value="item.value">
              <text>{{item.goodsName}}</text>
              <text class="padding-left">
                <text v-if="item.spec" class="text-sm">
                  <text v-if="item.spec == '大'" class="text-green text-bold">{{item.spec}}</text>
                  <text v-else-if="item.spec == '小'" class="text-blue text-bold">{{item.spec}}</text>
                  <text v-else>{{item.spec}}</text>
                </text>
              </text>
              <view class="cu-tag sm round" :class="item.checked?'bg-white text-orange':'bg-orange'" v-if="item.hot">HOT
              </view>
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        search: {},
        screen_show: 0,
        list: [{
          name: ''
        }],
        order_goods_list: [],
        scrollLeft: 0,
        cateList: [{
          id: 1,
          cate_name: '食用菌'
        }, {
          id: 2,
          cate_name: '神马商城'
        }],
        kw: '',
        modalName: 'goods_select_modal1',
        merName: '',
        phone: '',
        page: 1,
        currentDate: '',
        loadding: true,
        erpGoodsResult: {
          records: []
        },
        categoryName: "食用菌",
        goods_list: [{
          value: 0,
          name: '10元',
          checked: false,
          hot: false,
        }],
        order_discount: 100,
        order_info: {
          goods_count: 0,
          goodsAmount: 0.00,
        },
        selected_goods_ids: [],
        goods_list_by_key: {}
      }
    },

    onLoad(opt) {
      this.orderId = opt.id
      this.cate_id = opt.cate_id
      this.loadData();
      
      if (this.orderId) {
        this.loadOrderData()
      }
    },
    onNavigationBarButtonTap() {
      this.showModal()
    },
    methods: {
      doShowGoodsModal() {
        this.modalName = 'goods_select_modal'
      },
      doSelectGoods(item) {
        item.checked = !item.checked
      },
      doUpdateCard() {
        let that = this

        // 取出选择的商品
        let selected_goods_ids = []
        this.erpGoodsResult.records.forEach(function(item) {
          if (item.checked) {
            selected_goods_ids.push(item.id)
          }
        })

        // 先删除没有选择的订单商品
        let i = that.order_goods_list.length
        while (i--) {
          let _item = that.order_goods_list[i]
          let id_index = selected_goods_ids.indexOf(_item.id)
          if (id_index == -1) {
            that.order_goods_list.splice(i, 1)
          } else {
            selected_goods_ids.splice(id_index, 1)
          }
        }

        // 处理新选择的商品
        selected_goods_ids.forEach((item, i) => {
          that.order_goods_list.push(that.goods_list_by_key[item])
        })

        this.hideModal()
        this.doUpdateOrderItemAmount()
      },
      doUpdateOrderItemDiscount() {
        this.order_discount = parseInt(this.order_discount)
        if (this.order_discount > 100 || this.order_discount < 1) {
          this.order_discount = 100
        }

        this.order_goods_list.forEach(item => {
          item.discount = this.order_discount
        })

        this.doUpdateOrderItemAmount()
      },
      doUpdateOrderItemAmount() {
        let that = this
        this.order_goods_list.forEach(item => {
          let discount = item.discount ? parseInt(item.discount) : 100

          item.goodsAmount = item.goodsPrice * item.goodsNumber * discount / 100
        })

        // 计算总价格总数量
        let order_cnt = 0
        let order_amount = 0

        this.order_goods_list.forEach(function(item, i) {
          let discount = item.discount ? parseInt(item.discount) : 100
          // console.log(item)

          order_cnt += parseInt(item.goodsNumber)
          let goodsAmount = item.goodsPrice * parseInt(item.goodsNumber) * discount / 100
          that.order_goods_list[i]['goods_amount'] = goodsAmount
          order_amount += goodsAmount
        })

        this.order_info.goods_count = order_cnt
        this.order_info.goodsAmount = order_amount.toFixed(2)
      },
      doSaveOrder() {
        let that = this
        let url = '/erp/erpOrder/add';
        let orderData = {
          "amount": this.order_info.goodsAmount,
          "erpOrderItemsList": [],
          "orderType": "出库",
          "goodsCnt": this.order_info.goods_count,
          "orderSn": this.genOrderSn(),
        }

        orderData.erpOrderItemsList = that.order_goods_list
        this.$http.post(url, orderData).then(res => {
          console.log(res)
          uni.showToast({
            title: '添加成功',
            success() {
              uni.redirectTo({
                url: "/pages/erp/goods_order?type=chuku"
              })
            }
          })
        })
      },
      loadOrderData() {
        let that = this
        let url = '/erp/erpOrder/queryById?id=' + this.orderId;
        this.$http.get(url).then(res => {
      
          console.log(res.data.result)
          if (res.data.result) {
            that.order_info = {
              goods_count: res.data.result.goodsCnt,
              goodsAmount: res.data.result.amount,
            }
          }
        })
      
        url = '/erp/erpOrder/queryErpOrderItemsByMainId?id=' + this.orderId;
        this.$http.get(url).then(res => {
          that.order_goods_list = res.data.result
          // console.log(res.data.result)
          
          that.order_goods_list.forEach(item => {
            console.log(item.goodsName)
            item.shouzi = that.$getFristChar(item.goodsName)
          })
        })
      },
      reset() {
        this.search.name = "";
        this.search.phone = "";
        this.search.start_time = this.getDate({
          format: true
        });
        this.search.end_time = this.getDate({
          format: true
        });
      },
      searchResult() {
        this.page = 1;
        this.cate_id = 1

        this.hideModal()
        this.loadData()
      },
      screen() {
        // console.log('asdfasdf')
        var date = this.getDate({
          format: true
        });
        if (this.currentDate == "") {
          this.currentDate = date;
        }
        if (this.search.start_time == "") {
          this.search.start_time = date;
        }
        if (this.search.end_time == "") {
          this.search.start_time = date;
        }
        if (this.screen_show == 1) {
          this.screen_show = 0;
          document.body.parentNode.style.overflowY = "auto";
        } else {
          this.screen_show = 1;
          document.body.parentNode.style.overflowY = "hidden";
        }
      },
      getDate(type) {
        const date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        // if (type === 'start') {
        //   year = year - 60;
        // } else if (type === 'end') {
        //   year = year + 2;
        // }
        month = month > 9 ? month : '0' + month;;
        day = day > 9 ? day : '0' + day;
        return `${year}-${month}-${day}`;
      },
      genOrderSn() {
        let orderSn = this.getNowDate()
        orderSn = orderSn.replace(/[- :]/g, '') + parseInt(Math.random(1000, 9999) * 1000)
        return orderSn
      },
      getNowDate() {
        var myDate = new Date;
        var year = myDate.getFullYear(); //获取当前年
        var mon = myDate.getMonth() + 1; //获取当前月
        if (mon < 10) {
          mon = "0" + mon;
        }
        var date = myDate.getDate(); //获取当前日
        if (date < 10) {
          date = "0" + date;
        }
        var hours = myDate.getHours(); //获取当前小时
        if (hours < 10) {
          hours = "0" + hours;
        }
        var minutes = myDate.getMinutes(); //获取当前分钟
        if (minutes < 10) {
          minutes = "0" + minutes;
        }
        var seconds = myDate.getSeconds(); //获取当前秒
        if (seconds < 10) {
          seconds = "0" + seconds;
        }
        var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
        return now;
      },
      tabSelect(categoryName) {
        this.categoryName = categoryName;
        this.loadData()
      },
      loadData() {
        let that = this
        this.loadding = true

        let url = '/erp/erpGoods/list';
        this.$http.get(url, {
          params: {
            pageSize: 100,
            categoryName: that.categoryName
          }
        }).then(res => {
          this.loadding = false

          let result = res.data.result;
          let tmp_result = {
            records: []
          }
          result.records.forEach(_row => {
            _row.showzi = ""
            if (_row.goodsName.indexOf('卫') !== -1) {
              _row.shouzi = '卫'
            } else if (_row.goodsName.indexOf('响') !== -1) {
              _row.shouzi = '响'
            } else if (_row.goodsName.indexOf('韵') !== -1) {
              _row.shouzi = '韵'
            } else if (_row.goodsName.indexOf('响') !== -1) {
              _row.shouzi = '响'
            } else if (_row.goodsName.indexOf('阳') !== -1) {
              _row.shouzi = '阳'
            } else if (_row.goodsName.indexOf('如本') !== -1) {
              _row.shouzi = '本'
            } else {
              _row.shouzi = _row.goodsName.length > 0 ? _row.goodsName.substr(0, 1) : ""
            }

            _row.checked = false

            // console.log(_row.shouzi)
          })

          if (res.data.success) {
            this.erpGoodsResult = res.data.result
          }

          this.erpGoodsResult.records.forEach(item => {
            let discount = parseInt(item.sellingDiscount)
            if (!discount) {
              discount = 100
            }
            that.$set(this.goods_list_by_key, item.id, {
                "createBy": "",
                "createTime": "",
                "goodsId": item.id,
                "goodsName": item.goodsName,
                "goodsNumber": 1,
                "goodsPrice": item.sellingPrice,
                "goodsAmount": item.sellingPrice,
                "goodsSn": item.goodsSn,
                "goodsSpec": item.spec,
                "orderId": "",
                shouzi: item.shouzi,
                discount: '',
              }
              // ,{
              //   goods_id: item.id,
              //   shouzi: item.shouzi,
              //   goodsName: item.goodsName,
              //   goodsSpec: item.spec,
              //   discount: discount,
              //   goodsPrice: item.sellingPrice,
              //   goodsAmount: item.sellingPrice,
              //   goodsNumber: 1,
              // },
            )
          })

        }).catch(e => {
          this.loadding = false
          console.log(e)
        })
      },
      getCateList() {
        this.httpGet("merchant/listCate?page=").then(resp => {
          if (resp.data.status == "ok" && resp.data.result.list && resp.data.result.list.length > 0) {
            this.cateList = resp.data.result.list
          }
        });
      },
      makeCallDialog(e) {
        this.phone = e.currentTarget.dataset.phone
        this.merName = e.currentTarget.dataset.name
        if (this.phone) {
          this.modalName = e.currentTarget.dataset.target
        } else {
          this.httpGet('merchant/getPhone?mer_name=' + this.merName).then(resp => {
            if (resp.data.status == 'ok') {
              this.phone = resp.data.phone
              this.modalName = e.currentTarget.dataset.target
            }
          })

        }

      },
      makeCall() {
        uni.makePhoneCall({
          phoneNumber: this.phone
        })
      },
      showModal(e) {
        this.modalName = 'viewModal'
      },
      hideModal(e) {
        this.modalName = null
      },
      bindDateChange1: function(e) {
        this.search.start_time = e.target.value
      },
      bindDateChange2: function(e) {
        this.search.end_time = e.target.value
      },
    }
  }
</script>

<style lang="scss">
  @import url("../../static/drawer.css");
</style>
